/* 
 * 定义itfreerArcgis模块
 */
(function(window, angular, undefined){
	/* 
	 * 定义itfreerArcgis模块，用于map对象的初始化
	 */
	var itfreerarcgisModule = angular.module('itfreer.arcgis.map', 
		['itfreer.arcgis.draw',
		'itfreer.arcgis.geometryservice', 
		'itfreer.arcgis.locator', 
		'itfreer.arcgis.measure',
		'itfreer.arcgis.search',
		'itfreer.arcgis.book']);

	/**
	 * 定义核心模块依赖注入器，定义地图的基础用法
	 */
	itfreerarcgisModule.factory('$itfreer_arcgis_map',
		function($rootScope, $gisObject, $itfreer_core, $itfreer_arcgis_locator) {
			$itfreer_arcgis_map = {

				/**
				 * 设置政区服务
				 */
				setTiled : function(visible){
					for(attribute in $gisObject.BaseTiledLayer){
						if(visible){
							$gisObject.BaseTiledLayer[attribute].mapLayer.show();
						}else{
							$gisObject.BaseTiledLayer[attribute].mapLayer.hide();
						}
					} 
				},
				/**
				 * 返回视图
				 * **/
                 returnView:function(){
 			       	  $gisObject.map.setExtent($gisObject.fullExtent);
                 },
				/**
				 * 设置影像服务
				 */
				setImage : function(visible){
					for(attribute in $gisObject.BaseImageLayer){
						if(visible){
							$gisObject.BaseImageLayer[attribute].mapLayer.show();
						}else{
							$gisObject.BaseImageLayer[attribute].mapLayer.hide();
						}
					} 
				},

				/**
				 * 设置专题服务
				 */
				setServices : function(layer,isShow){
					if($gisObject.Services.hasOwnProperty(layer)){
						var visible = $gisObject.Services[layer].mapLayer.visible;
						visible = !visible;
						
						if(isShow != null){
							visible = isShow
						}

						if(visible){
							$gisObject.Services[layer].mapLayer.show();
						}else{
							$gisObject.Services[layer].mapLayer.hide();
						}
						return visible;
					}
				},
				
				/**
				 * 打印状态
				 */
				printStatus:{printing:false},
				
				/**
				 * 打印
				 */
				printImage : function() {
					if($gisObject.printingService){
						var template = new esri.tasks.PrintTemplate();
						template.exportOptions = { width: $gisObject.map.width, height: $gisObject.map.height, dpi: 96 };
						template.format = "PDF";
						template.layout = "MAP_ONLY";
						template.preserveScale = true;
						var params = new esri.tasks.PrintParameters();
						params.map = $gisObject.map;
						params.template = template;
						$itfreer_arcgis_map.printStatus.printing = true;
						$gisObject.printingService.execute(params, function(renderer) {
							if (renderer != null) {
								window.open(renderer.url);
							}
							$itfreer_arcgis_map.printStatus.printing = false;
						},function(error){
//							 $.messager.alert("错误", error.toString(),"error");
							 $itfreer_arcgis_map.printStatus.printing = false;
						});
					}
				}
			};
			for(f in $itfreer_arcgis_map){
				$rootScope[f] = $itfreer_arcgis_map[f];
			}
			return $itfreer_arcgis_map;
		}
	);

	/* 
	 * 定义arcgis map控件
	 */
	itfreerarcgisModule.directive('itfreerMap', 
		function($http, $gisObject,$itfreer_arcgis_locator, $itfreer_arcgis_geometryservice) {
		return {
			replace : true,
			restrict : 'E',
			template : '<div></div>',
			priority:99,
			link : function(scope, element, attrs, ctrl) {

				// 中心点
				var centerObject = eval(attrs.center);
				if(!centerObject){
					centerObject = [];
					centerObject.push(113.78279668);
					centerObject.push(22.6855779935);
				}

				var lods = eval(attrs.lods);
				if(!lods){
					lods = [
			             {"level" : 0, "resolution" : 1.40625, "scale" : 590995186.11750006},
			             {"level" : 1, "resolution" : 0.703125, "scale" : 295497593.05875003},
			             {"level" : 2, "resolution" : 0.3515625, "scale" : 147748796.52937502},
			             {"level" : 3, "resolution" : 0.17578125, "scale" : 73874398.264687508},
			             {"level" : 4, "resolution" : 0.087890625, "scale" : 36937199.132343754},
			             {"level" : 5, "resolution" : 0.0439453125, "scale" : 18468599.566171877},
			             {"level" : 6, "resolution" : 0.02197265625, "scale" : 9234299.7830859385},
			             {"level" : 7, "resolution" : 0.010986328125, "scale" : 4617149.8915429693},
			             {"level" : 8, "resolution" : 0.0054931640625, "scale" : 2308574.9457714846},
			             {"level" : 9, "resolution" : 0.00274658203125, "scale" : 1154287.4728857423},
			             {"level" : 10, "resolution" : 0.001373291015625, "scale" : 577143.73644287116},
			             {"level" : 11, "resolution" : 0.0006866455078125, "scale" : 288571.86822143558},
			             {"level" : 12, "resolution" : 0.00034332275390625, "scale" : 144285.93411071779},
			             {"level" : 13, "resolution" : 0.000171661376953125, "scale" : 72142.967055358895},
			             {"level" : 14, "resolution" : 0.0000858306884765625, "scale" : 36071.483527679447},
			             {"level" : 15, "resolution" : 0.0000429153442382812, "scale" : 18035.741763839724},
			             {"level" : 16, "resolution" : 0.0000214576721191406, "scale" : 9017.8708819198619},
			             {"level" : 17, "resolution" : 0.0000107288360595703, "scale" : 4508.9354409599309},
			             {"level" : 18, "resolution" : 5.36441802978515E-06, "scale" : 2254.4677204799655}
					];
				}else{
					var lodsCopy = [];
					lods.forEach(function(e){
						var item = {};
						item.level = parseInt(e.level);
						item.resolution = parseFloat(e.resolution);
						item.scale = parseFloat(e.scale);
						lodsCopy.push(item);
					});
					lods = lodsCopy;
				}

				var sliderlabels = eval(attrs.sliderlabels);
				if(!sliderlabels){
					sliderlabels = ["", "", "市 ", "县", "", "乡", "", "村", "", "", "", ""];
				}

				var zoom = 4;
				if(attrs.zoom){
					zoom = parseInt(attrs.zoom);
				}

				var maxZoom = 18;
				if(attrs.maxzoom){
					maxZoom = parseInt(attrs.maxzoom);
				}

				var minZoom = 0;
				if(attrs.minzoom){
					minZoom = parseInt(attrs.minzoom);
				}
				
				var slider = true;
				if(attrs.slider && attrs.slider=='true'){
					slider = true;
				}else{
					slider = false;
				}

				var initMap = function(){
					// 地理坐标系统
					if(attrs.dlwkid && attrs.dlwkid!=""){
						if($itfreer_core.validateNum(attrs.dlwkid)){
							var wkid = parseInt(attrs.dlwkid);
							$gisObject.dlwkid = new esri.SpatialReference({wkid: wkid});
						}else{
							$gisObject.dlwkid = new esri.SpatialReference(attrs.dlwkid);
						}
					}else{
						$gisObject.dlwkid = new esri.SpatialReference({wkid: 4326});
					}

					// 投影坐标系统
					if(attrs.tywkid && attrs.tywkid!=""){
						$gisObject.tywkid = parseInt(attrs.tywkid);
						if($itfreer_core.validateNum(attrs.tywkid)){
							var wkid = parseInt(attrs.tywkid);
							$gisObject.tywkid = new esri.SpatialReference({wkid: wkid});
						}else{
							$gisObject.tywkid = new esri.SpatialReference(attrs.tywkid);
						}
					}else{
						$gisObject.tywkid = new esri.SpatialReference({wkid: 102100});
					}

					// 当前的地图是否为地理坐标系统
					$gisObject.mapisdlwkid = true;
					if(attrs.mapisdlwkid && attrs.mapisdlwkid!=""){
						if(attrs.mapisdlwkid=="是"){
							$gisObject.mapisdlwkid = true;
						}else{
							$gisObject.mapisdlwkid = false;
						}
					}
					var wkid = null;
					if($gisObject.mapisdlwkid){
						wkid = $gisObject.dlwkid;
					}else{
						wkid = $gisObject.tywkid;
					}

					// 初始化地图
			        $gisObject.map = new esri.Map(attrs.id, {
						center : centerObject,
						sliderStyle : "large",
						lods : lods,
						sliderLabels : sliderlabels,
						zoom : true,
						maxZoom : attrs.maxzoom,
						minZoom : attrs.minzoom,
						logo : false,
						slider : true
					});
			        var scalebar = new esri.dijit.Scalebar({
			            map: $gisObject.map,
			            // "dual" displays both miles and kilometers
			            // "english" is the default, which displays miles
			            // use "metric" for kilometers
			            scalebarUnit: "metric"
			          });
			        if(attrs.initextent){
			        	var extentArray = attrs.initextent.split(",");
						var extent = new esri.geometry.Extent({
							"xmin" : parseFloat(extentArray[0]),
							"ymin" : parseFloat(extentArray[1]),
							"xmax" : parseFloat(extentArray[2]),
							"ymax" : parseFloat(extentArray[3]),
							"spatialReference" : wkid
						});
						$gisObject.fullExtent = extent;
						$gisObject.map.setExtent(extent);
			        }

					var layers = eval(attrs.layers);
					// {name:'bMapAnolayer',aliasName:'百度地图',group:'BaseImageLayer',mtype:'bMapAnolayer',url:'',visible:'是',showids:'0'}
					if(layers){
						layers.forEach(function(layer){
							var mapLayer = null;
							var visibleLayers = null;
							var layerName = layer.name;
							if(showids && showids!=""){
								visibleLayers = [];
								var ids = showids.split(",");
								ids.forEach(function(item){
									var intItem = parseInt(item);
									visibleLayers.push(intItem);
								});
							}

							if(layer.mtype == "ArcGISTiledMapServiceLayer"){
								// 瓦片地图服务
								mapLayer = new esri.layers.ArcGISTiledMapServiceLayer(layer.url,{id:layerName});
							} else if(layer.mtype == "ArcGISDynamicMapServiceLayer"){
								// 动态地图服务
								//set the image type to PNG24, note default is PNG8.
								var imageParameters = new esri.layers.ImageParameters();
						        imageParameters.format = "jpeg"; 
						        //Takes a URL to a non cached map service.
						        mapLayer = new esri.layers.ArcGISDynamicMapServiceLayer(layer.url, {
							        // "opacity" : 0.5,
							        "imageParameters" : imageParameters,
							        id:layerName,
							        visibleLayers: visibleLayers
						        });
							} else if(layer.mtype == "FeatureLayer"){
								// 要素服务
								mapLayer = new esri.layers.FeatureLayer(layer.url,{id:layerName});
							} else if(layer.mtype == "WMSLayer"){
								// WMS服务
								var showids = layer.showids;
								mapLayer = new esri.layers.WMSLayer(layer.url, {
						           format: "png",
						           id:layerName,
						           visibleLayers: visibleLayers
						        });
							} else if(layer.mtype == "WMTSLayer"){
								// WMTS服务
								var layerInfo = new esri.layers.WMTSLayerInfo({
						          	identifier: "opengeo:countries",
						          	tileMatrixSet: "EPSG:4326",
						          	format: "png"
						        });
						        var options = {
						          	serviceMode: "KVP",
						          	id:layerName,
						          	layerInfo: layerInfo
						        };
		        				mapLayer = new esri.layers.WMTSLayer(layer.url, options);
							} else if(layer.mtype == "ArcGISImageServiceLayer"){
								// 影像地图服务
								var params = new esri.layers.ImageServiceParameters();
						        params.noData = 0;
						        mapLayer = new esri.layers.ArcGISImageServiceLayer(layer.url, {
						          imageServiceParameters: params,
						          id:layerName,
						          opacity: 0.75
						        });
							} else if(layer.mtype == "bMapVeclayer"){
								// 百度地图政区服务
								mapLayer = this.arcGISObject.bmapVeclayer;
							} else if(layer.mtype == "bMapImglayer"){
								// 百度地图影像服务
								mapLayer = this.arcGISObject.bmapImglayer;
							} else if(layer.mtype == "bMapAnolayer"){
								// 百度地图标注服务
								mapLayer = this.arcGISObject.bmapAnolayer;
							} else if(layer.mtype == "tdMapAnnoLayer"){
								// 天地图基础地理标注服务
								mapLayer = this.arcGISObject.tdmapAnnoLayer;
							} else if(layer.mtype == "tdMapLayer"){
								// 天地图基础地理服务
								mapLayer = this.arcGISObject.tdmapLayer;
							} else if(layer.mtype == "tdMapImgAnnoLayer"){
								// 天地图影像标注服务
								mapLayer = this.arcGISObject.tdmapImgAnnoLayer;
							} else if(layer.mtype == "tdMapImgLayer"){
								// 天地图影像服务
								mapLayer = this.arcGISObject.tdmapImgLayer;
							}

							if(mapLayer){
								if(layer.visible != "是"){
									mapLayer.hide();
								}

								if(layer.group == "BaseTiledLayer"){
									// 政区服务
									$gisObject.BaseTiledLayer[layer.name] = {};
									$gisObject.BaseTiledLayer[layer.name].layer = layer;
									$gisObject.BaseTiledLayer[layer.name].mapLayer = mapLayer;
								} else if(layer.group == "BaseImageLayer"){
									// 影像服务
									$gisObject.BaseImageLayer[layer.name] = {};
									$gisObject.BaseImageLayer[layer.name].layer = layer;
									$gisObject.BaseImageLayer[layer.name].mapLayer = mapLayer;
								} else if(layer.group == "Services"){
									// 专题服务
									$gisObject.Services[layer.name] = {};
									$gisObject.Services[layer.name].layer = layer;
									$gisObject.Services[layer.name].mapLayer = mapLayer;
								}
								$gisObject.map.addLayer(mapLayer);
							}
						});
					}

					$gisObject.mapInit = true;
			        window.map = $gisObject.map;
			        // 初始化绘制对象
					$gisObject.navToolbar = new esri.toolbars.Navigation($gisObject.map);
					// 设置测量对象
		            $gisObject.drawToolbars = new esri.toolbars.Draw($gisObject.map);
		            $itfreer_arcgis_draw.init();
					//实例化GeometryService，地址为ags发布的GeometryServer
		            if(attrs.geometryservice && attrs.geometryservice!=""){
		            	$gisObject.geometryService = new esri.tasks.GeometryService(attrs.geometryservice);
		            	$itfreer_arcgis_geometryservice.init();
		            }
				};

				if(this.hasInitFinsh){
					initMap();
				}else{
					this.initFinshEvent = initMap;
				}
			}
		};
	});

	/* 
	 * 加载服务器
	 */
	itfreerarcgisModule.run(function($rootScope, $itfreer_arcgis_map) {
	  	
	});
}(window, angular));